package com.Utils.Tools;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLResponseParser {

    public static void main(String[] args) {
        String xmlResponse = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><ret_code>0000</ret_code><ret_msg>文件上传成功</ret_msg><agent_id>1664502</agent_id><file_id>17369335780440af485cc16645026064</file_id><sign>0eca786c8e2c770d3ebf7c1a9170288b</sign></root>";
        try {
            Map<String, String> elements = parseXML(xmlResponse);
            System.out.println(elements.get("ret_code"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> parseXML(String xml) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        Document doc = builder.parse(input);

        // 获取根元素
        Element root = doc.getDocumentElement();

        // 创建一个Map来存储键值对
        Map<String, String> elements = new HashMap<>();

        // 遍历<root>下的所有子元素
        NodeList nodeList = root.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            if (nodeList.item(i) instanceof Element) {
                Element element = (Element) nodeList.item(i);
                String tagName = element.getTagName();
                String value = element.getTextContent();
                elements.put(tagName, value);
            }
        }

        return elements;
    }
}